package com.oocl.jdbc_homework.bookstore;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.oocl.jdbc_homework.dao.BookDao;
import com.oocl.jdbc_homework.dao.impl.BookDaoImpl;
import com.oocl.jdbc_homework.pojo.Book;
import com.oocl.jdbc_homework.util.FileIOUtil;
import com.oocl.jdbc_homework.util.StringRandomUtil;

/**
 * 书店
 * 
 * @author WUJA13
 * 
 */
public class BookStore {

	BookDao bookDao;

	public BookStore() {
		bookDao = new BookDaoImpl();
	}

	/**
	 * 生成Book 数据 ， 并存入文件 `books.dat`中
	 * @param num
	 */
	public void saveBooksToFile(int num) {
		if (num <= 0)
			return;
		List<Book> list = new LinkedList<Book>();
		for (int i = 1; i <= num; i++) {
			String name = StringRandomUtil.getStringRandom(8);
			Date date = new Date();
			String author = StringRandomUtil.getStringRandom(5);
			boolean unuses = (int) (Math.random() * (10)) < 5 ? true : false;
			double price = 1234.56;
			String publisher = StringRandomUtil.getStringRandom(10);
			Book book = new Book(i, name, date, author, price, unuses,
					publisher);
			list.add(book);
		}
		
		long time = System.currentTimeMillis();
		FileIOUtil.saveObject("books.dat", list);
		time = System.currentTimeMillis() - time;
		System.out.println("保存到文件的时间：" + time);
		
	}

	/**
	 * 读取文件`D:/datas.dat` 中的数据， 并写入数据库
	 */
	public void saveBooksFromFileToOracle() {
		List<Book> list = null;
		list = (List<Book>) FileIOUtil.readObject("books.dat");
		
		long time = System.currentTimeMillis();
//		for (Book item : list) {
//			bookDao.addBook(item);
//		}
		bookDao.addBooks(list);
		time = System.currentTimeMillis() - time;
		System.out.println("存入数据库的时间："+ time);
		
	}

	public static void main(String[] args) {
		BookStore bookStore = new BookStore();
		bookStore.saveBooksToFile(10000);
		bookStore.saveBooksFromFileToOracle();
	}
}
